package com.jinhuhang.u2.myselfmodule.engine.user.register;

import android.content.Intent;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.fragment.ZSimpleBaseFragment;
import com.jinhuhang.u2.entity.RegisterBean;
import com.jinhuhang.u2.entity.UserSingleResult;
import com.jinhuhang.u2.entity.hto.RegisterHto;
import com.jinhuhang.u2.myselfmodule.engine.PhotoActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.DefaultLoginDialog;
import com.jinhuhang.u2.util.U2MD5Util;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.logger.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;

/**
 * Created by OnionMac on 17/9/15.
 */

public class RegisterNextFragment extends ZSimpleBaseFragment implements RegisterNextContract.View{

    @Bind(R.id.register_logo)
    ImageView mRegisterLogo;
    @Bind(R.id.registernext_phone)
    TextView mRegisternextPhone;
    @Bind(R.id.edt_register_phone)
    EditText mEdtRegisterPhone;
    @Bind(R.id.tv_register_send)
    TextView mTvRegisterSend;
    @Bind(R.id.edt_register_pwd)
    EditText mEdtRegisterPwd;
    @Bind(R.id.register_edt_recommend)
    EditText mRegisterEdtRecommend;
    @Bind(R.id.cb_regist_agree)
    CheckBox mCbRegistAgree;
    @Bind(R.id.tv_regist_xieyi)
    TextView mTvRegistXieyi;
    @Bind(R.id.tv_regist_xieyi2)
    TextView mTvRegistXieyi2;
    @Bind(R.id.btn_registernext)
    AppCompatButton mBtnRegisternext;
    private UserActivity mUserActivity;
    private String mKey;
    private RegisterNextContract.Presenter mPresenter;

    @Override
    protected void initView(View view) {
        mUserActivity = (UserActivity) getActivity();
        mRegisternextPhone.setText(mUserActivity.getPhone());
    }

    @Override
    public void onResultYzm(HttpWrapperList<UserSingleResult> o) {
        if(Constant.SUCCESS_CODE == o.code){
            mKey = o.getSingleData().getKey();
            Logger.i("短信验证码拿到的key:"+ mKey);

            /**
             * 计时开始
             */
            time();
        }else if(Constant.ERROR_201 == o.code){
            showMessage(o.getInfo());
        }
    }

    private void time() {
        Logger.i("验证码倒计时开始");
        mTvRegisterSend.setEnabled(false);
        addSubscription(UtilsCollection.countdown(59)            //倒计时60秒
                .subscribe(
                        time -> mTvRegisterSend.setText("重新发送"+"(" + time + ")"),    //每秒赋值
                        UtilsCollection::errorUtil,             //提示错误信息
                        () -> {
                            mTvRegisterSend.setEnabled(true);
                            mTvRegisterSend.setText(getString(R.string.reSendyzm));
                        }));
    }

    @Override
    protected void initListener() {
        RxView.clicks(mTvRegisterSend)
                .throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(vo -> {
                    String phone = mRegisternextPhone.getText().toString();
                    mPresenter.sendYzm(phone);
                });

        mBtnRegisternext.setOnClickListener(v -> {
            String yzm = mEdtRegisterPhone.getText().toString();
            String pwd = mEdtRegisterPwd.getText().toString();
            String recommend = mRegisterEdtRecommend.getText().toString();
            if(TextUtils.isEmpty(yzm)){
                showMessage("验证码不能为空!");
                return;
            }
            if(TextUtils.isEmpty(pwd)){
                showMessage("密码不能为空");
                return;
            }
            if(!UtilsCollection.check(pwd)){
                showMessage("请填写正确的密码格式");
                return;
            }

            if(!pwd.equals(recommend)){
                showMessage("两次输入的密码必须相同");
                return;
            }

            if(!mCbRegistAgree.isChecked()){
                showMessage("请勾选,我已阅读并同意相关条款");
                return;
            }

            RegisterHto registerHto = new RegisterHto();
            registerHto.setKey(mKey);
            registerHto.setInvitationCode(mUserActivity.getRecommend());
            registerHto.setMsg(yzm);
            registerHto.setPassword(pwd);
            registerHto.setPhone(mUserActivity.getPhone());

            Map<String,String> map = new HashMap<>();
            map.put("phone",mUserActivity.getPhone());
            map.put("password", U2MD5Util.encryption(pwd));
            map.put("invitationCode",mUserActivity.getRecommend());
            map.put("userId","0");
            map.put("msg",yzm);
            map.put("key",mKey);
            map.put("loginType",Constant.PLATFORM);
            mPresenter.register(map);
        });

        mTvRegistXieyi.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), PhotoActivity.class);
            intent.putExtra(PhotoActivity.TYPE,PhotoActivity.TYPE_REGISTER);
            startActivity(intent);
        });
        mTvRegistXieyi2.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), PhotoActivity.class);
            intent.putExtra(PhotoActivity.TYPE,PhotoActivity.TYPE_PRIVACY);
            startActivity(intent);
        });
    }

    @Override
    public void onResultRegister(HttpWrapperList<RegisterBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
            /**
             * 注册成功 去登录 TODO
             */
            DefaultLoginDialog defaultLoginDialog = new DefaultLoginDialog(getActivity());
            defaultLoginDialog.show();
            defaultLoginDialog.startCountDown();
            defaultLoginDialog.setOnCountDownEndListener(() -> {
                goLogin();
            });
            defaultLoginDialog.setOnNormalDialogLeftListener(() -> {
                goLogin();
            });
        }else if(Constant.ERROR_201 == o.code){
            showMessage(o.info);
        }
    }

    private void goLogin(){
        mUserActivity.startActivity(new Intent(mUserActivity,UserActivity.class));
        mUserActivity.finish();
    }

    @Override
    protected void attachPre() {
        mPresenter = new RegisterNextPresenter(this,getCompositeSubscription());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_registernext;
    }

}
